package cn.tp.ksoft.civil_driver.request;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.tp.ksoft.civil_driver.bean.BrandVo;
import cn.tp.ksoft.civil_driver.bean.DriverDto;
import cn.tp.ksoft.civil_driver.bean.EnterpriseDto;
import cn.tp.ksoft.civil_driver.bean.ResultBean;
import cn.tp.ksoft.civil_driver.utils.Constants;
import cn.tp.ksoft.civil_driver.utils.DeviceUtils;
import cn.tp.ksoft.civil_driver.utils.SystemPreference;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by zhusong on 16/5/4.
 */
public class DriverRequest extends BaseRequest implements RequestModules {
    public DriverRequest(Context context, Handler handler) {
        super(context, handler);
    }

    public void doRegister(DriverDto driverDto, String validateCode) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/register");
        mParams.setShowProgress(true);
        mParams.addDtoParams(driverDto);
        mParams.addParams("validateCode", validateCode);
        mParams.addParams("oper",OP_REGISTER);
        mParams.addDtoParams(DeviceUtils.getDeviceInfo(mContext.get()));
        mParams.setContext(mContext.get());
        final String telNumber = driverDto.getTelephone();
        doRequest(new SimpleProgressCall(mHandler, DOREGISTER) {
            @Override
            public void onResponse(ResultBean response) {
                SystemPreference.writeSystemValue(mContext.get(), SystemPreference.SYSTEM_USER_LOGIN_PHONENAME, telNumber);
                if (null != response && response.isSuccess()) {
                    SystemPreference.writeSystemValue(mContext.get(), SystemPreference.SYSTEM_VALUE_USER_TOKEN,
                            response.getData().toString());
                }
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }

    public void setPhoto(File file) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/setphoto.action");
        mParams.setShowProgress(false);
        mParams.addFile("photo", file);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, SETPHOTO) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }

    public void setLicense(File travel, File drive) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/setlicense.action");
        mParams.setShowProgress(true);
        mParams.addFile("travel", travel);
        mParams.addFile("drive", drive);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, SETLICENSE) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //完善或更新资料
    public void finishInfo(String name, String idCard, java.util.Date driverTime, String carNo,
                           String carBrand, String brandType, String carColor, Integer seat, Long enterpriseId) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/finishInfo.action");
        mParams.setShowProgress(false);
        mParams.addParams("name", name);
        mParams.addParams("idCard", idCard);
        mParams.addParams("driverTime", driverTime.getTime());
        mParams.addParams("carNo", carNo);
        mParams.addParams("carBrand", carBrand);
        mParams.addParams("brandType", brandType);
        mParams.addParams("carColor", carColor);
        mParams.addParams("seat", seat);
        mParams.addParams("enterpriseId", enterpriseId);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, FINISHINFO) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //获取单位列表
    public void getEnterprise() {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/getenterprise.action");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, GETENTERPRISE) {
            @Override
            public ResultBean parseNetworkResponse(Response response) throws Exception {
                ResultBean resultBean = parseBaseInfo(response);
                String dataStr = (String) resultBean.getData();
                if (resultBean.isSuccess() && !TextUtils.isEmpty(dataStr)) {
                    List<EnterpriseDto> data = new ArrayList<EnterpriseDto>();

                    JSONArray items = new JSONArray(dataStr);
                    for (int i = 0, len = items.length(); i < len; i++) {
                        EnterpriseDto enterpriseDto = new EnterpriseDto();
                        JSONObject item = items.optJSONObject(i);
                        enterpriseDto.setId(item.optLong("id"));
                        enterpriseDto.setName(item.optString("name"));
                        data.add(enterpriseDto);
                    }
                    resultBean.setData(data);
                }
                return resultBean;
            }

            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //获取基本信息
    public void getInfo() {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/getinfo.action");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, GETINFO) {
            @Override
            public ResultBean parseNetworkResponse(Response response) throws Exception {
                ResultBean user = parseBaseInfo(response);
                if (user.isSuccess() && !TextUtils.isEmpty((String)user.getData())) {
                    DriverDto driverDto = new DriverDto();
                    driverDto.parseJson(new JSONObject(user.getData().toString()));
                    user.setData(driverDto);
                }
                if(user.isKickedOut()){
                    LocalBroadcastManager.getInstance(mParams.getContext())
                            .sendBroadcast(new Intent(Constants.FILTER_SUFFIX));
                }
                return user;
            }

            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }

    //获取手机短信验证码
    public void getValidateCode(String telNumber, String oper) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/validate/getcode");
        mParams.setShowProgress(false);
        mParams.setContext(mContext.get());
        mParams.addParams("telNumber", telNumber);
        mParams.addParams("oper", oper );
        doRequest(new SimpleProgressCall(mHandler, GETVALIDATECODE) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }

    //是否常用设备
    public void isUsedDevice(String telNumber) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/isuseddevice");
        mParams.setContext(mContext.get());
        mParams.addParams("telNumber", telNumber);
        mParams.addDtoParams("driverDeviceDto", DeviceUtils.getDeviceInfo(mContext.get()));
        doRequest(new SimpleProgressCall(mHandler, ISUSEDDEVICE) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    /**
     * 登录
     * 分两种情况：
     * 		1. 登录时，如果没有报"非常用设备"，则直接登录
     * 		2. 登录时，返回非常用设备，则需要出现短信验证码框，获取短信验证码后再登录
     * @param telNumber		手机号码
     * @param loginPwd		密码
     * @param validateCode	短信校验码（非常用登录设备登录的情况下，需要传值）
     */
    //登录 (TODO:考虑请求应用最新版本，在打开应用异步或是登录返回)
    public void login(final String telNumber, String loginPwd, String validateCode) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/login");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        mParams.addParams("telNumber", telNumber);
        mParams.addParams("loginPwd", loginPwd);

        if(!TextUtils.isEmpty(validateCode)){
            mParams.addParams("oper", OP_LOGIN);
            mParams.addParams("validateCode", validateCode);
        }

        mParams.addDtoParams("driverDeviceDto", DeviceUtils.getDeviceInfo(mContext.get()));
        doRequest(new SimpleProgressCall(mHandler, LOGIN) {
            @Override
            public void onResponse(ResultBean response) {
                SystemPreference.writeSystemValue(mContext.get(), SystemPreference.SYSTEM_USER_LOGIN_PHONENAME, telNumber);
                if (null != response && response.isSuccess()) {
                    SystemPreference.writeSystemValue(mContext.get(), SystemPreference.SYSTEM_VALUE_USER_TOKEN,
                            response.getData().toString());
                }
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //修改登录密码
    public void modifyLoginPwd(String oldLoginPwd, String newLoginPwd) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/modifypassword.action");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        mParams.addParams("oldLoginPwd", oldLoginPwd);
        mParams.addParams("newLoginPwd", newLoginPwd);

        doRequest(new SimpleProgressCall(mHandler, MODIFYLOGINPWD) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //重置登录密码
    public void resetLoginPwd(final String telNumber, String password, String validateCode) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/resetloginpwd");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        mParams.addParams("telNumber", telNumber);
        mParams.addParams("password", password);
        mParams.addParams("oper", OP_RESET_PWD);
        mParams.addParams("validateCode", validateCode);

        doRequest(new SimpleProgressCall(mHandler, RESETLOGINPWD) {
            @Override
            public void onResponse(ResultBean response) {
                SystemPreference.writeSystemValue(mContext.get(), SystemPreference.SYSTEM_USER_LOGIN_PHONENAME, telNumber);

                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
    //校验手机短信验证码
    public void validateCode(String validateCode, String telNumber, String oper) {

    }

    //校验手机号码是否已注册
    public void validatePhone(String telNumber) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/validatephone");
        mParams.setShowProgress(false);
        mParams.setContext(mContext.get());
        mParams.addParams("telNumber", telNumber);
        doRequest(new SimpleProgressCall(mHandler, VALIDATEPHONE) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        } );
    }
    //登录校验token
    public void validateToken() {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/validatetoken.action");
        mParams.setShowProgress(false);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, VALIDATETOKEN) {

            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        } );
    }


    /***********For Brand*********/

    private ResultBean parseBrands(String string) throws Exception{
        ResultBean user = new ResultBean();
        JSONObject jsonObject = new JSONObject(string);
        user.setSuccess(jsonObject.optInt("returncode", -1) == 0);
        user.setTitle(jsonObject.optString("message"));
        JSONObject resultObj = jsonObject.optJSONObject("result");
        if (null != resultObj) {
            JSONArray arr = resultObj.optJSONArray("branditems");
            if (null != arr) {
                ArrayList<BrandVo> list = new ArrayList<BrandVo>(arr.length());
                for (int i = 0, len = arr.length(); i < len; i++) {
                    JSONObject item = arr.optJSONObject(i);
                    BrandVo vo = new BrandVo();
                    vo.setId(item.optInt("id"));
                    vo.setName(item.optString("name"));
                    vo.setFirstletter(item.optString("bfirstletter"));
                    list.add(vo);
                }
                user.setData(list);
            }
        }

        return user;
    }

    private ResultBean parseBrandModel(String string) throws Exception {
        ResultBean user = new ResultBean();
        JSONObject jsonObject = new JSONObject(string);
        user.setSuccess(jsonObject.optInt("returncode", -1) == 0);
        user.setTitle(jsonObject.optString("message"));
        JSONObject resultObj = jsonObject.optJSONObject("result");
        if (null != resultObj) {
            JSONArray arr = resultObj.optJSONArray("factoryitems");
            if (null != arr) {
                ArrayList<BrandVo> list = new ArrayList<BrandVo>(arr.length());
                for (int i = 0, len = arr.length(); i < len; i++) {
                    JSONObject item = arr.optJSONObject(i);
                    JSONArray seriesitems = item.optJSONArray("seriesitems");
                    if (null == seriesitems) {
                        continue;
                    }
                    for (int j = 0, lenj = seriesitems.length(); j < lenj; j++) {
                        BrandVo vo = new BrandVo();
                        JSONObject sItem = seriesitems.optJSONObject(j);
                        vo.setId(sItem.optInt("id"));
                        vo.setName(sItem.optString("name"));
                        vo.setFirstletter(sItem.optString("firstletter"));
                        list.add(vo);
                    }
                }
                user.setData(list);
            }
        }

        return user;
    }

    private ExecutorService mThread = Executors.newSingleThreadExecutor();
    //http://www.autohome.com.cn/ashx/AjaxIndexCarFind.ashx?type=1
    public void getBrandList() {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip("www.autohome.com.cn");
        mParams.setProject_name("ashx");
        mParams.setModel_name("");
        mParams.setServlet_name("AjaxIndexCarFind.ashx");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        mParams.addParams("type", 1);
        File dir = mContext.get().getExternalCacheDir();
        if (null != dir && !dir.exists()) {
            dir.mkdirs();
        }
        final File brandFile = new File(dir, "brands.data");
        final SimpleProgressCall call = new SimpleProgressCall(mHandler, GETBRANDLIST) {
            @Override
            public ResultBean parseNetworkResponse(Response response) throws Exception {
                String string = response.body().string();

                BufferedWriter br = new BufferedWriter(new FileWriter(brandFile));
                br.write(string);
                br.close();

                return parseBrands(string);
            }

            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        };

        // file exist, read from sdcard
        if (brandFile.exists()) {
            call.onBefore(null);
            mThread.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(brandFile));
                        StringBuffer sb = new StringBuffer();
                        String line;
                        while( (line = br.readLine()) != null) {
                            sb.append(line);
                        }
                        br.close();

                        call.onResponse(parseBrands(sb.toString()));

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                call.onAfter();
                            }
                        });
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            return;
        }

        doRequest(call);
    }

    //http://www.autohome.com.cn/ashx/AjaxIndexCarFind.ashx?type=3&value=117
    public void getBrandModelList(int id) {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip("www.autohome.com.cn");
        mParams.setProject_name("ashx");
        mParams.setModel_name("");
        mParams.setServlet_name("AjaxIndexCarFind.ashx");
        mParams.setShowProgress(true);
        mParams.setContext(mContext.get());
        mParams.addParams("type", 3);
        mParams.addParams("value", id);

        File dir = mContext.get().getExternalCacheDir();
        if (null != dir && !dir.exists()) {
            dir.mkdirs();
        }
        final File brandFile = new File(dir, "brands_"+id+".data");

        final SimpleProgressCall call = new SimpleProgressCall(mHandler, GETBRANDMODELLIST) {
            @Override
            public ResultBean parseNetworkResponse(Response response) throws Exception {
                String string = response.body().string();

                BufferedWriter br = new BufferedWriter(new FileWriter(brandFile));
                br.write(string);
                br.close();

                return parseBrandModel(string);
            }

            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }

            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        };
        // file exist, read from sdcard
        if (brandFile.exists()) {
            call.onBefore(null);
            mThread.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(brandFile));
                        StringBuffer sb = new StringBuffer();
                        String line;
                        while( (line = br.readLine()) != null) {
                            sb.append(line);
                        }
                        br.close();

                        call.onResponse(parseBrandModel(sb.toString()));

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                call.onAfter();
                            }
                        });
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            return;
        }

        doRequest(call);
    }
    //获取设备列表
    public void getDeviceList() {
        if (checkRecycle()) {
            return;
        }
        mParams = new RequestParams();
        mParams.setServer_ip(Constants.REQUEST_SERVER_IP);
        mParams.setProject_name(Constants.REQUEST_PROJECT);
        mParams.setModel_name(Constants.REQUEST_MODEL);
        mParams.setServlet_name("driver/device/list.action");
        mParams.setShowProgress(false);
        mParams.setContext(mContext.get());
        doRequest(new SimpleProgressCall(mHandler, GETLASTESTFLIGHTORDER) {
            @Override
            public void onResponse(ResultBean response) {
                super.onResponse(response);
            }
            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }
        });
    }
}
